package com.david.func_test.view

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LayoutAnimationController
import android.widget.PopupWindow
import androidx.recyclerview.widget.RecyclerView
import com.david.func_test.R
import com.david.func_test.util.MyLayoutAnimationHelper

class AlbumCarChoosePop(anchor: View, context: Context, var clickFun: ((Int) -> Unit)? = null) : PopupWindow() {


    init {
        val view = LayoutInflater.from(context).inflate(R.layout.popup_album_car_choose, null)
        contentView = view
        width = ViewGroup.LayoutParams.MATCH_PARENT
        height = (anchor.parent as View).height - (anchor.bottom)
        isTouchable = true
        isOutsideTouchable = true
        view.setOnClickListener {
            dismiss()
        }
        val list = view.findViewById<RecyclerView>(R.id.test)


        val controller = LayoutAnimationController(MyLayoutAnimationHelper.getAnimationSetFromTop())
        controller.delay = 0.1f
//        controller.order =
//            if (isReverse) LayoutAnimationController.ORDER_REVERSE else LayoutAnimationController.ORDER_NORMAL

        list.setLayoutAnimation(controller)
        list.getAdapter()?.notifyDataSetChanged()
        list.scheduleLayoutAnimation()



        list.adapter = CarChoosePopListAdapter(clickFun)
        if ((list?.adapter?.itemCount?:0) >= 4) {
            list.layoutParams.height = (396 * anchor.context.resources.displayMetrics.density).toInt()
        }
        this.setBackgroundDrawable(ColorDrawable(Color.parseColor("#80000000")))

//        animationStyle = R.style.popup_animation
    }
}

class CarChoosePopListAdapter(var clickFunc: ((Int) -> Unit)? = null): RecyclerView.Adapter<CarChoosePopHolder>() {
    var lastSelectPosition = 0
    private val clickListener = View.OnClickListener {
        lastSelectPosition = it.tag as Int
        notifyDataSetChanged()

        clickFunc?.invoke(lastSelectPosition)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarChoosePopHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.car_choose_pop_item, parent, false)
        view.setOnClickListener(clickListener)
        view.setBackgroundResource(R.drawable.car_choose_bg)
        return CarChoosePopHolder(view)
    }

    override fun onBindViewHolder(holder: CarChoosePopHolder, position: Int) {
        holder.itemView.tag = position
        holder.itemView.isSelected = lastSelectPosition == position
    }

    override fun getItemCount(): Int {
        return 4
    }

}

class CarChoosePopHolder(item: View): RecyclerView.ViewHolder(item) {

}